package cn.g31010.sip.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.Map;

public class IDUtil {

	private DecimalFormat df;
	private long id;
	private boolean closed;
	private File file;
	private static Map<String,IDUtil> ids = new HashMap<String,IDUtil>();
	private IDUtil(String name) {
		df = new DecimalFormat();
		load(name);
		Runtime.getRuntime().addShutdownHook(new Thread(){
			public void run(){
				save();
			}
		});
	}
	
	public void setPattern(String pattern){
		df.applyPattern(pattern);
	}
	
	public static IDUtil getIntance(String name){
		if(!ids.containsKey(name)){
			ids.put(name, new IDUtil(name));
		}
		return ids.get(name);
	}

	private void load(String resource) {
		resource=resource.replace(".properties", "").replace(".", "/");
		URL url = Thread.currentThread().getContextClassLoader().getResource(resource+".properties");
		if (url != null) {
			file=new File(url.getFile());
			BufferedReader br = null;
			try {
				System.out.println("load "+url.getFile());
				br = new BufferedReader(new InputStreamReader(url.openStream()));
				String ln = br.readLine();
				if (ln != null) {
					id = Long.decode(ln);
				}
				System.out.println("load "+url.getFile()+" ok");
			} catch (IOException e) {
				e.printStackTrace();
			} finally {
				if (br != null) {
					try {
						br.close();
					} catch (IOException e) {
					}
				}
			}
		}
	}

	private synchronized void save() {
		if(file==null)
			return;
		System.out.println("save "+file);
		closed=true;
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file, false);
			out.write(String.valueOf(id).getBytes());
			out.flush();
			System.out.println("save "+file+" ok");
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			if(out!=null){
				try {
					out.close();
				} catch (IOException e) {
				}
			}
		}
	}

	public String genId() {
		return df.format(id());
	}

	public String genId(String pattern) {
		df.applyPattern(pattern);
		return df.format(id());
	}

	private synchronized long id() {
		if(closed){
			throw new RuntimeException("system is exit.");
		}
		id += 1;
		return id;
	}
	
	public static void main(String args[]){
		IDUtil idu = IDUtil.getIntance("cn.g31010.sip.util.uid");
		idu.setPattern("UID0000");
		for(int i=0;i<100;i++){
			System.out.println(idu.genId());
		}
		
	}
}
